package com.guojian.jdbc.transaction;

import javax.sql.DataSource;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.guojian.jdbc.DataSourceFactory;

import lombok.extern.slf4j.Slf4j;

/**
 * 事务管理器
 * 
 * @author guojian
 *
 */
@Slf4j
public class TransactionManager {

	private TransactionManager() {
	}

	public static boolean beginTransaction(String dataSourceName, Itransaction transaction) {
		DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(DataSourceFactory.getDataSource(dataSourceName));
		TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
		try {
			transaction.execute();
			transactionManager.commit(status);
		} catch (Exception e) {
			log.error("=========执行失败,操作将回滚=====> {}", e.getMessage());
			transactionManager.rollback(status);
			return false;
		}
		return true;
	}

	public static String transactionTemplate(DataSource dataSource, Itransaction transaction) {
		DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
		TransactionTemplate template = new TransactionTemplate(transactionManager);
		return template.execute(new TransactionCallback<String>() {
			@Override
			public String doInTransaction(TransactionStatus status) {
				transaction.execute();
				return null;
			}
		});

	}

	public static void main(String[] args) {

	}

}
